package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.MessageSenderContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.properties.MessageSenderProperties;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.MessageSender;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowMessageVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowMessageRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

/**
 * @author lilh
 * @date 2020/12/2 上午9:29
 */
@Slf4j
@Service
@EnableConfigurationProperties(MessageSenderProperties.class)
public class DefaultMessageSender implements MessageSender {

    @Autowired
    private FlowMessageRepository messageRepository;

    @Autowired
    private MessageSenderProperties properties;

    @Override
    public boolean isEnable() {
        return properties.getSystem().isEnable();
    }

    @Override
    public boolean sendMessage(MessageSenderContext context) {
        FlowMessageVo message = resolveMessage(context);
        log.info("插入一条系统消息：{}", JSONObject.toJSONString(message));
        return messageRepository.insertMessage(message);
    }

    @Override
    public String getDescription() {
        return "系统消息";
    }

    private FlowMessageVo resolveMessage(MessageSenderContext context) {
        FlowMessageVo message = new FlowMessageVo();
        message.setMsgType(context.getType());
        message.setMsgTitle(context.getTitle());
        message.setMsgBoby(context.getBody());
        message.setReceiverCode(context.getReceiverCode());
        message.setReceiverName(context.getReceiverName());
        message.setSenderCode(context.getSenderCode());
        message.setSenderName(context.getSenderName());
        message.setCreateTime(new Date());
        message.setProcessName(context.getProcessName());
        message.setProcessInstanceId(context.getProcessInstanceId());
        message.setTaskId(context.getTaskId());
        message.setStatus(0);
        return message;
    }
}
